<?php
/*
 * @Author: 孙开源 && sunkaiyuan@namenode.cn
 * @Date: 2023-04-12 16:45:39
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @LastEditTime: 2023-04-12 17:12:45
 * @Description: 
 * 
 */
namespace szzhijing\Kernel\Responses;

use szzhijing\Kernel\Exceptions\InvalidArgumentException;

class StreamResponse extends Response
    {
    /**
     * @param string $directory
     * @param string $filename
     *
     * @throws \szzhijing\Kernel\Exceptions\InvalidArgumentException
     *
     * @return string
     */
    public function save(string $directory, string $filename = '') : string
        {
        $this->getBody()->rewind();

        $directory = rtrim($directory, '/');

        if (!is_dir($directory)) {
            mkdir($directory, 0755, true); // @codeCoverageIgnore
            }

        if (!is_writable($directory)) {
            throw new InvalidArgumentException(sprintf("'%s' is not writable.", $directory));
            }

        $contents = $this->getBody()->getContents();

        if (empty($filename)) {
            if (preg_match('/filename="(?<filename>.*?)"/', $this->getHeaderLine('Content-Disposition'), $match)) {
                $filename = $match['filename'];
                }
            else {
                $filename = md5($contents);
                }
            }

        file_put_contents($directory . '/' . $filename, $contents);

        return $filename;
        }

    /**
     * @param string $directory
     * @param string $filename
     *
     * @throws \szzhijing\Kernel\Exceptions\InvalidArgumentException
     *
     * @return string
     */
    public function saveAs(string $directory, string $filename) : string
        {
        return $this->save($directory, $filename);
        }
    }